package com.gewu.pm.ui.activity;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.gewu.pm.R;
import com.gewu.pm.aop.DebugLog;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.http.callback.DialogCallback;
import com.gewu.pm.http.model.HttpData;
import com.gewu.pm.http.request.LoginApi;
import com.gewu.pm.http.response.LoginBean;
import com.gewu.pm.manager.InputTextManager;
import com.gewu.pm.other.IntentKey;
import com.gewu.pm.other.KeyboardWatcher;
import com.gewu.pm.ui.MainActivity;
import com.gewu.pm.ui.fragment.MeFragment;
import com.gewu.pm.utils.PersonalUtils;
import com.hjq.http.EasyHttp;
import com.hjq.http.config.IRequestApi;

/**
 * 登录界面
 */
public final class LoginActivity extends AppActivity
        implements KeyboardWatcher.SoftKeyboardStateListener,
        TextView.OnEditorActionListener {

    @DebugLog
    public static void start(Context context, String phone, String password) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.putExtra(IntentKey.PHONE, phone);
        intent.putExtra(IntentKey.PASSWORD, password);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    private ImageView mLogoView;
    private ViewGroup mBodyLayout;
    private EditText mPhoneView;
    private EditText mPasswordView;

    private View mForgetView;
    private TextView tvRegister;
    private Button mCommitView;
    private TextView tvAgree;//协议
    private CheckBox cbLogin;

    /**
     * logo 缩放比例
     */
    private final float mLogoScale = 0.8f;
    /**
     * 动画时间
     */
    private final int mAnimTime = 300;

    @Override
    protected int getLayoutId() {
        return R.layout.login_activity;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mLogoView = findViewById(R.id.iv_login_logo);
        mBodyLayout = findViewById(R.id.ll_login_body);
        mPhoneView = findViewById(R.id.et_login_phone);
        mPasswordView = findViewById(R.id.et_login_password);
        mForgetView = findViewById(R.id.tv_login_forget);
        mCommitView = findViewById(R.id.btn_login_commit);
        tvRegister = findViewById(R.id.tv_login_register);
        tvAgree = findViewById(R.id.tv_login_agree);
        cbLogin = findViewById(R.id.cb_login);

        setOnClickListener(mForgetView, tvRegister, mCommitView);

        mPasswordView.setOnEditorActionListener(this);

        InputTextManager.with(this)
                .addView(mPhoneView)
                .addView(mPasswordView)
                .setMain(mCommitView)
                .build();
    }

    @Override
    protected void initData() {
        postDelayed(() -> {
            KeyboardWatcher.with(LoginActivity.this)
                    .setListener(LoginActivity.this);
        }, 500);

        // 自动填充手机号和密码
        mPhoneView.setText(getString(IntentKey.PHONE));
        mPasswordView.setText(getString(IntentKey.PASSWORD));

        setHyperlink();
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        if (view == mForgetView) {
            startActivity(PasswordForgetActivity.class);
        } else if (view == tvRegister) {// 跳转到注册界面
            RegisterActivity.start(this, mPhoneView.getText().toString(),
                    mPasswordView.getText().toString(), (phone, password) -> {
                        // 如果已经注册成功，就执行登录操作
                        mPhoneView.setText(phone);
                        mPasswordView.setText(password);
                        mPasswordView.requestFocus();
                        mPasswordView.setSelection(mPasswordView.getText().length());
                        onClick(mCommitView);

                    });
        } else if (view == mCommitView) {
            if (!cbLogin.isChecked()) {
                toast("请阅读并同意使用协议");
                return;
            }
            if (mPhoneView.getText().toString().length() != 11) {
                mPhoneView.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.shake_anim));
                toast(R.string.common_phone_input_error);
                return;
            }

            // 隐藏软键盘
            hideKeyboard(getCurrentFocus());

            EasyHttp.get(this)
                    .api(new LoginApi()
                            .setMobile(mPhoneView.getText().toString())
                            .setCode(mPasswordView.getText().toString()))
                    .request(new DialogCallback<HttpData<LoginBean>>(this) {

                        @Override
                        public void onHttpEnd(@NonNull IRequestApi api) {
                        }

                        @Override
                        public void onHttpSuccess(HttpData<LoginBean> data) {
                            LoginBean bean = data.getData();
                            if (bean == null) {
                                return;
                            }
                            PersonalUtils.setPersonal(LoginActivity.this,data.getData());
                            postDelayed(() -> {
                                // 跳转到首页
                                MainActivity.start(getContext(), MeFragment.class);
                                finish();
                            }, 1000);
                        }

                        @Override
                        public void onHttpFail(@NonNull Throwable e) {
                            super.onHttpFail(e);

                        }
                    });
        }
    }

    /**
     * 设置文字的超链接 各种协议
     */
    private void setHyperlink() {
        SpannableString spannableString = new SpannableString("我已阅读并同意《服务协议》和《隐私政策》");

        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                toast("0");
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setUnderlineText(false);//因为设置了超链接 有下划线 去掉下划线
                ds.setColor(getResources().getColor(R.color.red_app));
            }
        }, 7, 13, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                toast("1");
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setUnderlineText(false);//因为设置了超链接 有下划线 去掉下划线
                ds.setColor(getResources().getColor(R.color.red_app));
            }
        }, 14, 20, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //然后把spannableString放进到Text中
        tvAgree.setText(spannableString);
        //中途遇到点击后字体显示高亮，取消高亮
        tvAgree.setHighlightColor(Color.parseColor("#00000000"));
        //最后设置可点击，必须实现，否则只能显示样式，无法实现点击效果
        tvAgree.setMovementMethod(LinkMovementMethod.getInstance());
    }
    /**
     * {@link KeyboardWatcher.SoftKeyboardStateListener}
     */

    @Override
    public void onSoftKeyboardOpened(int keyboardHeight) {
        // 执行位移动画
        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mBodyLayout, "translationY", 0, -mCommitView.getHeight());
        objectAnimator.setDuration(mAnimTime);
        objectAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        objectAnimator.start();

        // 执行缩小动画
        mLogoView.setPivotX(mLogoView.getWidth() / 2f);
        mLogoView.setPivotY(mLogoView.getHeight());
        AnimatorSet animatorSet = new AnimatorSet();
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(mLogoView, "scaleX", 1f, mLogoScale);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(mLogoView, "scaleY", 1f, mLogoScale);
        ObjectAnimator translationY = ObjectAnimator.ofFloat(mLogoView, "translationY", 0f, -mCommitView.getHeight());
        animatorSet.play(translationY).with(scaleX).with(scaleY);
        animatorSet.setDuration(mAnimTime);
        animatorSet.start();
    }

    @Override
    public void onSoftKeyboardClosed() {
        // 执行位移动画
        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mBodyLayout, "translationY", mBodyLayout.getTranslationY(), 0f);
        objectAnimator.setDuration(mAnimTime);
        objectAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        objectAnimator.start();

        if (mLogoView.getTranslationY() == 0) {
            return;
        }

        // 执行放大动画
        mLogoView.setPivotX(mLogoView.getWidth() / 2f);
        mLogoView.setPivotY(mLogoView.getHeight());
        AnimatorSet animatorSet = new AnimatorSet();
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(mLogoView, "scaleX", mLogoScale, 1f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(mLogoView, "scaleY", mLogoScale, 1f);
        ObjectAnimator translationY = ObjectAnimator.ofFloat(mLogoView, "translationY", mLogoView.getTranslationY(), 0f);
        animatorSet.play(translationY).with(scaleX).with(scaleY);
        animatorSet.setDuration(mAnimTime);
        animatorSet.start();
    }

    /**
     * {@link TextView.OnEditorActionListener}
     */
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE && mCommitView.isEnabled()) {
            // 模拟点击登录按钮
            onClick(mCommitView);
            return true;
        }
        return false;
    }
}